package com.jhz.speedy.common.util.encrypt;

import android.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * AES加密工具
 * Created by JunHeZ on 2017/7/7.
 */
public class AESUitls implements IEncrypt{

    private String TAG = AESUitls.class.getCanonicalName();

    private static AESUitls instance;

//    public static final String ALGORITHM = "AES/CBC/PKCS5Padding";
    private static final String ALGORITHM = "AES/CBC/PKCS7Padding";

    private static final String CHARSETNAME = "UTF-8";

    /**
     * 密钥，必须是16的倍数
     */
    private static final String key = "kSTWuwVyH9YCnNnR";

    /**
     * 向量字符串
     * 这里已经
     */
    private static final String ivStr = "3138995984284342";

    private static IvParameterSpec iv;

    private AESUitls() {
        byte[] ivBytes = ivStr.getBytes();
        iv = new IvParameterSpec(ivBytes);
    }

    public static AESUitls getInstance() {
        if (instance == null)
            instance = new AESUitls();
        return instance;
    }

    /**
     * 加密数据
     *
     * @param data 需要加密的内容
     * @return
     */
    public String encryptData(String data) {
        try {
            byte rs[] = encrypt(data.getBytes(), key.getBytes(), Cipher.ENCRYPT_MODE);
            return Base64.encodeToString(rs, Base64.NO_WRAP);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;

    }

    /**
     * 解密数据
     *
     * @param data 需要解密的内容
     * @return
     */
    public String decryptData(String data) {
        try {
            byte rs[] = encrypt(Base64.decode(data.getBytes(), Base64.NO_WRAP), key.getBytes(), Cipher.DECRYPT_MODE);
            return new String(rs, CHARSETNAME);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;

    }

    /**
     * 加解密
     *
     * @param data 数据
     * @param key  密钥
     * @param mode 加密还是解密
     */
    private static byte[] encrypt(byte[] data, byte[] key, int mode) throws Exception {
        SecretKeySpec skeySpec = new SecretKeySpec(key, ALGORITHM);
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(mode, skeySpec, iv);
        byte[] encrypted = cipher.doFinal(data);
        return encrypted;
    }

}

    